package client;

import java.io.*;
import java.net.*;
import java.util.Scanner;

class MESServer
{	
	//Socket related fields for communicating with the MES server
	private Socket mesServer;
	private BufferedReader reader;
	private PrintWriter output;
	
	protected static boolean responseReceived;
		
	String sendCommandToMES(String toSend)
	{
		try
		{
			mesServer = new Socket(InetAddress.getByName("192.168.0.100"), 80);
			output = new PrintWriter(mesServer.getOutputStream());
			reader = new BufferedReader(new InputStreamReader(mesServer.getInputStream()));
		}
		catch (UnknownHostException e)
		{
			System.out.println("UnknownHostException");
			e.printStackTrace();
		}
		catch (IOException e)
		{
			System.out.println("Connection problems. System will exit");
			e.printStackTrace();
			System.exit(0);
		}
		
		SendCommandThread senderThread = new SendCommandThread(output, toSend);
		senderThread.start();
		
		while (true)
		{
			try
			{ while (!reader.ready()) {} }
			catch (IOException e1)
			{ e1.printStackTrace(); }
			
			try
			{
				StringBuilder sb = new StringBuilder();	
				while (reader.ready())
				{
					String temp = reader.readLine();
					sb.append(temp).append("\n");
				}
				System.out.println(sb.toString());
				
				mesServer.close();
				output.close();
				reader.close();
				
				return sb.toString();
			}
			catch (IOException e)
			{}
		}
	}
}

class SendCommandThread extends Thread
{	
	private PrintWriter output;
	private String command;
	
	SendCommandThread(PrintWriter o, String c)
	{
		output = o;
		command = c + "\n\n";
	}
	
	public void run()
	{
		output.write(command);
		output.flush();
		MESServer.responseReceived = false;
		System.out.println(command);
	}
}